package com.greenantmall.home;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.greenantmall.R;
import com.greenantmall.actionbar.ActionBar;
import com.greenantmall.actionbar.ActionBarItem;
import com.greenantmall.actionbar.LoaderActionBarItem;
import com.greenantmall.actionbar.NormalActionBarItem;
import com.greenantmall.actionbar.ActionBar.OnActionBarListener;
import com.greenantmall.actionbar.ActionBarItem.Type;
import com.greenantmall.activity.BaseActivity;
import com.greenantmall.activity.DetailActivity;
import com.greenantmall.activity.GoodsListTradeStyleActivity;
import com.greenantmall.activity.LoginActivity;
import com.greenantmall.activity.SearchActivity;
import com.greenantmall.activity.ShoppingCartActivity;
import com.greenantmall.bean.GoodsStyles;
import com.greenantmall.bean.UIGoods;

public class ActivityIndependentStoreHome extends BaseActivity {

	private ActionBar mActionBar;
	private PopupMenu popup =null;
	private final Handler mHandler = new Handler();
	private TextView storeAddr;
	private TextView openTime;
	private TextView startPrice;
	private ImageView openStatus;
	private GridView gvStoreStyle;
	private GridView gvStoreCabinet;
	private TextView tvStoreCabinetName;
	private TextView tvStoreCabinetMore;
	private List<StoreStyleInfo> storeStyleInfoList;
	private List<GoodsInfo> goodsInfoList;
	private LinearLayout LayoutStoreHome;
	private Handler handler=null;
	private String sectionId;
	private List<AVObject> myStores=null;
	private int popupSelectItem;
	private List<View> viewList;
	private String storeId=null;
	private String userId =null;
	private AVObject curStore=null;
	private boolean popmenuInit =false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_independent_store_home);

		popmenuInit =false;
        storeStyleInfoList=new ArrayList<StoreStyleInfo>();
        
        sectionId = getIntent().getStringExtra("mySection");        
        storeId = getIntent().getStringExtra("myStore");       
        
        viewList = new ArrayList<View>();        
        avsCloudQuery();          
        
        initHandler();

		storeAddr = (TextView)findViewById(R.id.tvStoreAddr);
		openTime = (TextView)findViewById(R.id.openTimes);
		startPrice = (TextView)findViewById(R.id.minusPirce);
		openStatus = (ImageView)findViewById(R.id.ivOpenStatus);
		gvStoreStyle =  (GridView)findViewById(R.id.gv_independent_store_style);
		LayoutStoreHome =(LinearLayout)findViewById(R.id.l_store_home);		
				
		// 针对type是normal的情况
		mActionBar = (ActionBar) findViewById(R.id.gd_action_bar);
		
		popup=new PopupMenu(ActivityIndependentStoreHome.this, mActionBar.getTitleView());
		
		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				popupSelectItem = item.getItemId()-Menu.FIRST;
				curStore=myStores.get(popupSelectItem);
				showStoreInfo(curStore);					
				return true;
			}
		});
		// 添加右边的具体的item，其实是imagebutton
		// 它内部自己封装了一些type，比如refresh、search，主要就是直接使用它内置的一些图片作为imagebutton的src
		// 后面是该imagebutton的id，可以在values/ids.xml中定义
		// 刷新跟其他type有所不一样，除了一个imagebutton，还有一个progressbar，下面可看到
		mActionBar.setType(ActionBar.Type.IndependentStore);
	//	mActionBar.addItem(Type.Refresh, R.id.action_bar_refresh);
		mActionBar.addItem(Type.Search, R.id.action_bar_search);
		// 你也可以按照下面一样自己添加一个item，设置自己的图片
		mActionBar.addItem(
				mActionBar.newActionBarItem(NormalActionBarItem.class)
						.setDrawable(R.drawable.store_cart)
						.setContentDescription("cart"), R.id.action_bar_cart);
		if (sectionId==null){
			mActionBar.showActitionBarTitleIcon(View.GONE);
		}
		// 给item即imagebutton添加监听事件
		mActionBar.setOnActionBarListener(new OnActionBarListener() {

			@Override
			public void onActionBarItemClicked(int position) {

				if (position == ActionBar.OnActionBarListener.HOME_ITEM) {

					// 当按左边的主页按钮时所触发的操作			
					System.gc();
					finish();
					return;
				}
				if (position == ActionBar.OnActionBarListener.TITLE_ITEM) {			
					if (popmenuInit){
						popup.show();
					}					
					return;
				}

				final ActionBarItem item = mActionBar.getItem(position);

				switch (item.getItemId()) {
				case R.id.action_bar_refresh:
					if (item instanceof LoaderActionBarItem) {

						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								// 通过这个方法可以来显示和隐藏那个progressbar
								((LoaderActionBarItem) item).setLoading(false);
							}
						}, 2000);
					}

				/*	Toast.makeText(ActivityIndependentStoreHome.this, "refresh",
							Toast.LENGTH_SHORT).show();*/
					break;

				case R.id.action_bar_search:
					if (curStore==null||curStore!=null&&curStore.getString("status").equals("CLOSED")){
						break;
					}
					// 你具体的操作
//					Toast.makeText(ActivityIndependentStoreHome.this, "search",
//							Toast.LENGTH_SHORT).show();
					Intent intentSearch = new Intent(ActivityIndependentStoreHome.this, SearchActivity.class);
					//storeId = (storeId == null ? "" : storeId);
					startActivity(intentSearch);
					break;

				case R.id.action_bar_cart:

					// 你具体的操作
//					Toast.makeText(ActivityIndependentStoreHome.this, "cart",
//							Toast.LENGTH_SHORT).show();
					if (curStore==null||curStore!=null&&curStore.getString("status").equals("CLOSED")){
						break;
					}
					if(AVUser.getCurrentUser() == null) {
						Intent intent = new Intent(ActivityIndependentStoreHome.this, LoginActivity.class);
						startActivity(intent);
					}
					else {
						Intent intentCart = new Intent(ActivityIndependentStoreHome.this, ShoppingCartActivity.class);
						intentCart.putExtra(ShoppingCartActivity.KEY_SP_SHOPPING_CART, false);
						intentCart.putExtra(ShoppingCartActivity.KEY_STORE_ID, userId);
						startActivity(intentCart);
					}
					break;

				}
			}
		});
	}	

	private void initStoreStyleGrid(){				
        
		if (storeStyleInfoList==null){
			return;
		}
		AdapterGridStoreStyle sa=new AdapterGridStoreStyle(this);
		sa.setList(storeStyleInfoList);
		gvStoreStyle.setAdapter(sa);
		gvStoreStyle.setOnItemClickListener(new OnItemClickListener() 
        { 
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
            { 
               // Toast.makeText(ActivityIndependentStoreHome.this, "pressed" + position, Toast.LENGTH_SHORT).show(); 
            	
               /*Intent intent = new Intent();//"android.intent.action.MYSTORE");
               intent.setClass(IndependentStoreHomeActivity.this,xx.class);
               startActivity(intent);*/
              
				if(storeStyleInfoList != null) {
					StoreStyleInfo ssi = storeStyleInfoList.get(position);
					if(ssi != null && ssi.getGoodsStylesList() != null) {
						ArrayList<String> goodsStylesNameList = new ArrayList<String>();
						List<GoodsStyles> goodsStylesList = ssi.getGoodsStylesList();
						for(GoodsStyles gs : goodsStylesList) {
							String name = gs.getName();
							goodsStylesNameList.add(name);
							Log.d("CEXX", "CEXX ---> gs.getName() : " + name);
						}
						Intent intent = new Intent(ActivityIndependentStoreHome.this, GoodsListTradeStyleActivity.class);
						intent.putExtra(GoodsListTradeStyleActivity.KEY_GOODS_STYLES_LIST, goodsStylesNameList);
						intent.putExtra(GoodsListTradeStyleActivity.KEY_GOODS_STYLES_STORE_ID, userId);
						ActivityIndependentStoreHome.this.startActivity(intent);
					}
				}
            } 
        }); 
		gvStoreStyle.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}	
	
	private void initCabinet(InnerClass inner){	
        
			View v = getLayoutInflater().inflate(R.layout.item_store_cabinet, null);
			
			viewList.add(v);
			
			tvStoreCabinetName =  (TextView)v.findViewById(R.id.tv_cabinet_name);
			tvStoreCabinetMore =  (TextView)v.findViewById(R.id.tv_cabinet_more);
			gvStoreCabinet =  (GridView)v.findViewById(R.id.gv_cabinet);
			tvStoreCabinetName.setText(inner.getObject().getString("title"));
			
			tvStoreCabinetMore.setTag(inner.getTag());
			
			initStoreCabinetGrid(inner.getList());
			initStoreStyleGrid();
			LayoutStoreHome.addView(v);
	}
	
	private void initStoreCabinetGrid(final List<GoodsInfo> list){				
		
		AdapterGridStoreCabinet sa=new AdapterGridStoreCabinet(this);
		sa.setList(list);
		gvStoreCabinet.setAdapter(sa);
		gvStoreCabinet.setOnItemClickListener(new OnItemClickListener() 
        { 
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
            { 
                GoodsInfo goodsInfo = list.get(position);
                if(goodsInfo != null) {
                	Intent intent = new Intent(ActivityIndependentStoreHome.this, DetailActivity.class);
                    intent.putExtra(DetailActivity.KEY_DETAIL_OBJECTID, goodsInfo.getId());
                    ActivityIndependentStoreHome.this.startActivity(intent); 
                }
            } 
        }); 
		gvStoreCabinet.setSelector(new ColorDrawable(Color.TRANSPARENT));
		
		tvStoreCabinetMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				//直接把list传给新的acitivity
				
				ArrayList<UIGoods> uiGoodsList = new ArrayList<UIGoods>();
				for(GoodsInfo goods : list) {
					UIGoods ug = new UIGoods();
        			ug.setObjectId(goods.getId());
        			ug.setDescroption(goods.getDesc());
        			ug.setSpecs(goods.getSpecs());
//        			ug.setDiscount(goods.getDiscount());
        			ug.setPicUrl(goods.getUrl());
        			
        			try{
        				ug.setPriceAfterDiscount(Double.valueOf(goods.getPrice()));
        			}
        			catch(Exception e) {
        				e.printStackTrace();
        			}
        			
//        			ug.setShowTag(goods.getShowTag());
//        			ug.setUnit(goods.getUnit());
//        			ug.setStepUnit(goods.getWeighUnit());
//        			ug.setStep(goods.getWeighStep());
//        			ug.setPricePrevious(goods.getOriginalPrice());
//        			ug.setPriceByWeight(goods.isWeighAble());
//        			ug.setBuyedPeopleCount(goods.getTotalSales());
        			ug.setStock(goods.getStock());
        			uiGoodsList.add(ug);
				}
				if(storeStyleInfoList != null) {
					int positon = (Integer)view.getTag();
					if (positon>storeStyleInfoList.size()){
						positon= storeStyleInfoList.size();
					}						
					StoreStyleInfo ssi = storeStyleInfoList.get(positon);
					if(ssi != null && ssi.getGoodsStylesList() != null) {
						ArrayList<String> goodsStylesNameList = new ArrayList<String>();
						List<GoodsStyles> goodsStylesList = ssi.getGoodsStylesList();
						for(GoodsStyles gs : goodsStylesList) {
							String name = gs.getName();
							goodsStylesNameList.add(name);
						}
						Intent intent = new Intent(ActivityIndependentStoreHome.this, GoodsListTradeStyleActivity.class);
						intent.putExtra(GoodsListTradeStyleActivity.KEY_GOODS_STYLES_LIST, goodsStylesNameList);
						intent.putExtra(GoodsListTradeStyleActivity.KEY_GOODS_STYLES_STORE_ID, userId);
						ActivityIndependentStoreHome.this.startActivity(intent);
					}
				}
			}
		});
        
		//gvStoreCabinet.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}
	private void queryCabinet(AVObject object,int tag){
		AVRelation<AVObject> relation = object.getRelation("cabinet");
        
        try {
        	List<AVObject> list=relation.getQuery().find();
        	
        	goodsInfoList=new ArrayList<GoodsInfo>();
           	
           	for (AVObject obj : list) {		            	
           		GoodsInfo info = new GoodsInfo();
	            	info.setDesc(obj.getString("description"));
	            	info.setSpecs(obj.getString("specs"));
	            	info.setUrl(obj.getAVFile("image").getUrl());
	                info.setPrice(obj.getNumber("price").toString());
	                info.setId(obj.getObjectId());
	                goodsInfoList.add(info);           
	        }
           	InnerClass inner = new InnerClass(tag);
           	inner.setObject(object);
           	inner.setList(goodsInfoList);
           	handler.sendMessage(handler.obtainMessage(0, inner));
		} catch (AVException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}        
	}
	
	private void queryIndependentStoreBySection(String sectionId){
		
		String sServerSection="ServerSection";
		AVObject mySection = new AVObject(sServerSection);
		AVQuery<AVObject> querySection = new AVQuery<AVObject>(sServerSection);
		
		if (sectionId==null){
			return;
		}
		try {
			mySection = querySection.get(sectionId);
			AVQuery<AVObject> storeQuery = AVRelation.reverseQuery("StoreInfo","uptowns",mySection);
			
			myStores=storeQuery.find();
			
			Menu menu = popup.getMenu();
			int i=0;
			for (AVObject obj : myStores) {		            	
            	//StoreStyleInfo styleInfo = new StoreStyleInfo(); 	
            	menu.add(Menu.NONE, Menu.FIRST + i, 0, obj.getString("descrip"));  
            	i++;
            	
	        }			
		} catch (AVException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
		popmenuInit =true;
	}
	
    private void queryIndependentStoreById(String storeId){
		
    	if (storeId==null){
			return;
		}
		String sStore="StoreInfo";
		curStore = new AVObject(sStore);
		AVQuery<AVObject> queryStore = new AVQuery<AVObject>(sStore);
		
		try {
			curStore = queryStore.get(storeId);
			userId = curStore.getString("userId");
			handler.sendMessage(handler.obtainMessage(1,curStore));			
		} catch (AVException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}				
	}
	
	private void queryStoreInfo() {
		if (curStore==null){
			return;
		}
		synchronized (this) { 
		    AVQuery<AVObject> styleQuery = new AVQuery<AVObject>("IndependentStoreGoodsStyle");
			styleQuery.whereEqualTo("userId", curStore.getString("userId"));
			userId = curStore.getString("userId");
			styleQuery.orderByAscending("showIndex");
			int index =0;
			try {
				List<AVObject> list= styleQuery.find();
				storeStyleInfoList.clear();
				for (AVObject obj : list) {		            	
	            	StoreStyleInfo styleInfo = new StoreStyleInfo(); 	
	            	styleInfo.setStoreStyleId(obj.getObjectId());
	            	if (obj.getAVFile("icon")!=null)
	            	{
	            		styleInfo.setUrl(obj.getAVFile("icon").getUrl());//锟斤拷锟酵硷拷锟斤拷锟皆达拷锟絀D 
	            	}
	                styleInfo.setTitle(obj.getString("title"));
	                styleInfo.setSubtitle(obj.getString("subtitle"));
	                
	                AVRelation<GoodsStyles> relation = obj.getRelation("subStyleList");
	                AVQuery<GoodsStyles> query1 = relation.getQuery();
	                try
	                {
	                	styleInfo.setGoodsStylesList(query1.find()); 
	                } catch (AVException e)
	                {
	                    e.printStackTrace();
	                }
	                
	                storeStyleInfoList.add(styleInfo);     
	                queryCabinet(obj,index);
	                index++;
		        }
			//handler.sendMessage(handler.obtainMessage(0, list));
		} catch (AVException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	    }					
	}
	
	private void initHandler(){
		try {
            //handler与线程之间的通信及数据处理
            handler = new Handler(){
                public void handleMessage(Message msg) {
                    if(msg.what==0){
                        //msg.obj是获取handler发送信息传来的数据
                        InnerClass inner =(InnerClass) msg.obj;                        
                        initCabinet(inner);                        
                    }else if (msg.what==1){
                    	AVObject store = (AVObject)msg.obj;
                    	showStoreInfo(store);
                    }
                }
            };
        }catch (Exception e){
            e.printStackTrace();
        }    
	}
	
	void avsCloudQuery(){
		Thread t = new Thread(newTread);
        t.start();
	}
	
	void storeInfoQuery(){
		Thread t = new Thread(storeInfoTread);
        t.start();
	}
	
	Runnable newTread = new Runnable() {
		 
        @Override
        public void run() {
        	queryIndependentStoreBySection(sectionId);
        	queryIndependentStoreById(storeId);
        }
 
    };
    
    Runnable storeInfoTread = new Runnable() {
		 
        @Override
        public void run() {
        	queryStoreInfo();
        }
 
    };
    
    private class InnerClass{
    	private AVObject object;
    	private List<GoodsInfo> list;
    	private int tag;
    	
    	public InnerClass(int tag) {
			// TODO Auto-generated constructor stub
    		this.list =new ArrayList<GoodsInfo>();
    		this.tag =tag;
		}
		public AVObject getObject() {
			return object;
		}
		public void setObject(AVObject object) {
			this.object = object;
		}
		public List<GoodsInfo> getList() {
			return list;
		}
		public int getTag(){
			return tag;
		}
		public void setList(List<GoodsInfo> goodsInfoList) {
			this.list = goodsInfoList;
		}
    	
    };
    
    private void showStoreInfo(AVObject store){
    	storeId = store.getObjectId();
    	Log.d("CEXX", "CEXX ---> showStoreInfo ---> storeId : " + storeId);
    	
    	mActionBar.setTitle(store.getString("descrip"));
		storeAddr.setText(store.getString("subAddr"));
		openTime.setText(store.getString("openTime")+
				"-"+store.getString("closeTime"));
		startPrice.setText("¥"+store.getNumber("startCost"));
		if (store.getString("status").equals("CLOSED"))
		{
			openStatus.setImageResource(R.drawable.shop_resting);
		}
		else
		{
			openStatus.setImageResource(R.drawable.shop_opening);
			storeInfoQuery();
		}	
		for (View v : viewList) {		            	
			LayoutStoreHome.removeView(v);    
        }
		
    }
}
